/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pneuservis.frontend.web;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.SessionScope;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pneuservis.backend.others.OrderStatus;
import pneuservis.backend.services.CustomerServiceLocal;
import pneuservis.backend.services.OrderPneuServiceLocal;
import pneuservis.backend.services.ServicePneuServiceLocal;
import pneuservis.backend.services.TyreTypeServiceLocal;
import pneuservis.backend.to.CustomerTO;
import pneuservis.backend.to.OrderPneuTO;
import pneuservis.backend.to.ServicePneuTO;
import pneuservis.backend.to.TyreTypeTO;

/**
 *
 * @author Admin
 */
@UrlBinding("/{$event}")
@SessionScope
public class IndexActionBean implements ActionBean {

    private ActionBeanContext context;
    final static Logger log = LoggerFactory.getLogger(CustomersActionBean.class);
    @EJB(lookup = "java:global/cz.muni.fi.pa165.pneuservis_Pneuservis-ear_ear_1.0-SNAPSHOT/Pneuservis-ejb-1.0-SNAPSHOT/OrderPneuService")
    private OrderPneuServiceLocal orderPneuService;
    @EJB(lookup = "java:global/cz.muni.fi.pa165.pneuservis_Pneuservis-ear_ear_1.0-SNAPSHOT/Pneuservis-ejb-1.0-SNAPSHOT/CustomerService")
    private CustomerServiceLocal customerService;
    @EJB(lookup = "java:global/cz.muni.fi.pa165.pneuservis_Pneuservis-ear_ear_1.0-SNAPSHOT/Pneuservis-ejb-1.0-SNAPSHOT/ServicePneuService")
    private ServicePneuServiceLocal servicePneuService;
    @EJB(lookup = "java:global/cz.muni.fi.pa165.pneuservis_Pneuservis-ear_ear_1.0-SNAPSHOT/Pneuservis-ejb-1.0-SNAPSHOT/TyreTypeService")
    private TyreTypeServiceLocal tyreTypeService;
    @ValidateNestedProperties(value = {
        @Validate(on = {"orderConfirm"}, field = "name", required = true),
        @Validate(on = {"orderConfirm"}, field = "address", required = true),
        @Validate(on = {"orderConfirm"}, field = "phone", required = true),
        @Validate(on = {"orderConfirm"}, field = "username", required = true),
        @Validate(on = {"orderConfirm"}, field = "password", required = true, converter=PasswordTypeConverter.class)
    })
    private CustomerTO customer;    
    private TyreTypeTO tyre;
    @ValidateNestedProperties(value = {
        @Validate(on = {"neworder"}, field = "tyresCount", required = true),
        @Validate(on = {"neworder"}, field = "vehicleBrand", required = true)
    })
    private OrderPneuTO order;
    private List<Long> checkedServices = new ArrayList<>();

    public List<Long> getCheckedServices() {
        return checkedServices;
    }

    public void setCheckedServices(List<Long> checkedServices) {
        this.checkedServices = checkedServices;
    }

    public CustomerTO getCustomer() {
        return customer;
    }

    public void setCustomer(CustomerTO customer) {
        this.customer = customer;
    }

    public OrderPneuTO getOrder() {
        return order;
    }

    public void setOrder(OrderPneuTO order) {
        this.order = order;
    }

    public TyreTypeTO getTyre() {
        return tyre;
    }

    public void setTyre(TyreTypeTO tyre) {
        this.tyre = tyre;
    }

    @Override
    public void setContext(ActionBeanContext abc) {
        this.context = abc;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    public List<TyreTypeTO> getTyres() {
        return tyreTypeService.getAllTyreTypes();
    }

    public List<ServicePneuTO> getServices() {
        return servicePneuService.getAllServices();
    }

    public List<CustomerTO> getCustomers() {
        return customerService.getAllCustomers();
    }

    public Resolution orderExistingCustomer() {
        customer = customerService.getCustomerByUsername(SecurityUtils.getSubject().getPrincipal().toString());
        try {
            List<ServicePneuTO> list = new ArrayList<>();
            for (Long id : checkedServices) {
                list.add(servicePneuService.getService(id));
            }
            order.setCustomer(customer);
            order.setStatus(OrderStatus.PREPARATION);
            order.setTyreType(tyre);
            order.setServicePneus(list);
            log.warn("Creating order: "+order+" with customer: "+customer.toString());
            orderPneuService.createOrder(order);
            
            return new ForwardResolution("thanks.jsp");
        } catch (EJBException ex) {
            log.warn(ex.getMessage());
        }

        return new ForwardResolution("order.jsp");
    }

    public Resolution orderConfirm() {
        try {
            List<ServicePneuTO> list = new ArrayList<>();
            for (Long id : checkedServices) {
                list.add(servicePneuService.getService(id));
            }
            order.setCustomer(customer);
            order.setStatus(OrderStatus.PREPARATION);
            order.setTyreType(tyre);
            order.setServicePneus(list);
            orderPneuService.createOrderWithCustomer(order);
            
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(customer.getUsername(), customer.getPassword()));
            
            return new ForwardResolution("thanks.jsp");
        } catch (EJBException ex) {
            log.warn(ex.getMessage());
        }
        return new ForwardResolution("/order.jsp");
    }

    public Resolution neworder() {
        return new ForwardResolution("/order.jsp");
    }

    public Resolution buy() {
        String id = context.getRequest().getParameter("buytyre");
        if (id != null) {
            tyre = tyreTypeService.getTyreType(Long.parseLong(id));
            if(tyre != null) {
                return new ForwardResolution("buy.jsp");
            }
        }
        return new RedirectResolution(this.getClass());
    }

    @DefaultHandler
    @DontValidate
    public Resolution all() {
        order = null;
        customer = null;
        tyre = null;
        checkedServices = new ArrayList<>();
        return new ForwardResolution("index.jsp");
    }
}
